<template>
    <div class="mod-config">
        <!--  头部：新增，批量删除    -->
        <div>
            <!--    新增按钮      -->
            <el-button type="primary" icon="el-icon-circle-plus-outline" @click="addCourse()">新增</el-button>
            <!--    手动刷新     -->
            <el-button type="primary" icon="el-icon-refresh" @click="refresh()">刷新</el-button>
            <!--    批量删除      -->
            <el-button type="danger" icon="el-icon-delete" @click="deleteRows(dataList)" :disabled="dataList.length <= 0">批量删除</el-button>
            <el-form :inline="true" :model="dataForm"  ref="dataForm" style="float:right">
                <el-form-item>
                    <el-button @click="searchHandle()" type="primary" icon="el-icon-search">搜 索</el-button>
                </el-form-item>
                <el-form-item>
                    <el-input v-model="name" placeholder="搜索课程名称如:健身" size="medium" class="input" clearable="clearable"></el-input>
                </el-form-item>
            </el-form>

        </div>
        <el-divider></el-divider>
        <!--   主体：表格（基本信息，修改，删除）   -->
        <div class="table">
            <el-table :data="tableData" border style="width: 100%" v-loading="dataListLoading" @selection-change="selectionChangeHandle">
                <el-table-column type="selection" header-align="center" align="center" width="50">
                </el-table-column>
                <el-table-column type="index" header-align="center" align="center" width="100" label="序号">
                    <template #default="scope">
                        <span>{{ (currentPage - 1) * pageSize + scope.$index + 1 }}</span>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="课程名称" width="150"></el-table-column>
                <el-table-column prop="desc" label="课程描述" width="230" align="center"></el-table-column>
                <el-table-column prop="cover" label="课程封面" width="120" align="center">
                    <template slot-scope="scope">
                        <el-image style="width: 100px; height: 100px" :src="scope.row.cover"></el-image>
                    </template>
                </el-table-column>
                <el-table-column prop="url" label="课程视频URL" width="180" align="center">
                    <template slot-scope="scope">
                        <el-link :underline="false" :href="scope.row.url" target="_blank" type="primary"><i
                                class="el-icon-view el-icon--right"></i>【点击查看】
                        </el-link>
                    </template>
                </el-table-column>
                <el-table-column prop="tags" label="课程标签" width="120" align="center">
                    <template slot-scope="scope">
                        <el-tag type="info" v-text="scope.row.tags" v-if="scope.row.tags=='下肢增强'"></el-tag>
                        <el-tag type="success" v-text="scope.row.tags" v-else-if="scope.row.tags=='有氧减脂'"></el-tag>
                        <el-tag type="danger" v-text="scope.row.tags" v-else-if="scope.row.tags=='核心力量'"></el-tag>
                        <el-tag type="primary" v-text="scope.row.tags" v-else></el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="calorie" label="卡路里" width="120" align="center"></el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="120" align="center">
                    <template slot-scope="scope">
                        {{ new Date(scope.row.createTime).toLocaleString() }}
                    </template>
                </el-table-column>
                <el-table-column prop="modifyTime" label="修改时间" width="120" align="center">
                    <template slot-scope="scope">
                        {{ new Date(scope.row.modifyTime).toLocaleString() }}
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="200" align="center">
                    <template slot-scope="scope">
                        <el-button @click="updateRow(scope.row.id)" size="small" icon="el-icon-edit" type="primary">
                            修改
                        </el-button>
                        <el-button @click="deleteRow(scope.row.id)" size="small" icon="el-icon-delete" type="danger">
                            删除
                        </el-button>
                    </template>
                </el-table-column>

            </el-table>
            <el-pagination
					align="left"
                    @current-change="changePage"
                    background
                    layout="total, prev, pager, next"
                    :page-size="pageSize"
                    :current-page="currentPage"
                    :total="total">
            </el-pagination>
        </div>
        <!--   弹窗-新增课程  -->
        <el-dialog title="新增课程数据" :visible.sync="editFormVisibleForAdd" :show-close="isClose" :close-on-click-modal="isClose">
            <el-form :model="dataForm" :rules="dataRules" label-width="120px">
                <el-form-item label="课程名称:" prop="name">
                    <el-input v-model="dataForm.name" placeholder="课程名称比如：快乐的游泳技巧">
                    </el-input>
                </el-form-item>
                <el-form-item label="课程描述:" prop="desc">
                    <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 4}" placeholder="游泳是一门技巧"
                              maxlength="200" show-word-limit v-model="dataForm.desc">
                    </el-input>
                </el-form-item>
                <el-form-item label="课程封面" prop="cover">
                    <el-upload action="' '" list-type="picture-card" accept=".jpg,.jpeg,.png" :before-upload="beforeUploadHandle" style="float: left" v-loading="this.loading">
                        <img width="100%" v-if="this.dataForm.cover" :src="this.dataForm.cover" height="100%">
                        <i  v-else class="el-icon-plus"></i>
                    </el-upload>
                    <el-button type="primary" v-if="this.dataForm.cover" icon="el-icon-upload2" style="margin-top: 50px;margin-left: 10px" @click="removeHandle()">重新上传</el-button>
                </el-form-item>
                <el-form-item label="课程视频:" prop="url">
                    <el-upload action="' '" accept=".mp4,.avi,.wmv,.asf,.rm,.mpeg,.m4v,.vob,.3gp" drag :before-upload="uploadHandle" style="float: left" v-if="!dataForm.url" v-loading="this.loading">
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">仅支持.mp4,.avi,.wmv,.asf,.rm,.mpeg,.m4v,.vob,.3gp格式的视频</div>
                    </el-upload>
                    <el-link :underline="false" :href="dataForm.url" target="_blank" type="primary" v-if="dataForm.url"><i
                        class="el-icon-view el-icon--right"></i>【点击查看】
                    </el-link>
                    <el-button type="primary" v-if="dataForm.url" icon="el-icon-upload2" style="margin-left: 10px" @click="removeVideo()">重新上传</el-button>
                </el-form-item>
                <el-form-item label="课程标签:" prop="tags">
                    <el-select v-model="dataForm.tags" placeholder="请选择">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="卡路里:" prop="calorie">
                    <el-input v-model="dataForm.calorie" placeholder="卡路里比如：100">
                    </el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancleAdd()">取 消</el-button>
                <el-button type="primary" @click="handleAdd()">确 定</el-button>
            </div>
        </el-dialog>
        <!--   弹窗-修改课程  -->
        <el-dialog title="修改课程数据" :visible.sync=" editFormVisibleForUpdate" :show-close="isClose" :close-on-click-modal="isClose">
            <el-form :model="dataForm"  label-width="120px">
                <el-form-item label="课程名称:" prop="name">
                    <el-input v-model="dataForm.name" placeholder="课程名称比如：快乐的游泳技巧">
                    </el-input>
                </el-form-item>
                <el-form-item label="课程描述:" prop="desc">
                    <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 4}" placeholder="游泳是一门技巧"
                              maxlength="200" show-word-limit v-model="dataForm.desc">
                    </el-input>
                </el-form-item>
                <el-form-item label="课程封面:" prop="cover">
                    <img v-if="this.dataForm.cover" :src="this.dataForm.cover" height="100px" width="100px" style="float: left">
                    <el-button type="primary" v-if="this.dataForm.cover" icon="el-icon-document-copy" style="margin-top: 28px;margin-left: 10px" @click="removeHandle()">覆盖原版</el-button>
                    <el-upload action="' '" list-type="picture-card" accept=".jpg,.jpeg,.png" :before-upload="beforeUploadHandle" style="float: left" v-if="!dataForm.cover" v-loading="this.loading">
                        <img width="100%" v-if="this.dataForm.cover" :src="this.dataForm.cover" height="100%">
                        <i  v-else class="el-icon-plus"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="课程视频:" prop="url">
                    <el-link :underline="false" :href="dataForm.url" target="_blank" type="primary" v-if="dataForm.url"><i
                        class="el-icon-view el-icon--right"></i>【点击查看】
                    </el-link>
                    <el-button type="primary" v-if="dataForm.url" icon="el-icon-document-copy" style="margin-left: 10px" @click="removeVideo()">覆盖原版</el-button>
                    <el-upload action="' '" accept=".mp4,.avi,.wmv,.asf,.rm,.mpeg,.m4v,.vob,.3gp" drag :before-upload="uploadHandle" style="float: left" v-if="!dataForm.url" v-loading="this.loading">
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">仅支持.mp4,.avi,.wmv,.asf,.rm,.mpeg,.m4v,.vob,.3gp格式的视频</div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="课程标签:" prop="tags">
                    <el-select v-model="dataForm.tags" placeholder="请选择">
                        <el-option
                            v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="卡路里:" prop="calorie">
                    <el-input v-model="dataForm.calorie" placeholder="卡路里比如：100">
                    </el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancleUpdate(id)">取 消</el-button>
                <el-button type="primary" @click="handleUpdate(id)">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data() {
        return {
            // 课程列表
            tableData: [],
            // 当前页
            currentPage: this.$router.currentRoute.query.page ? parseInt(this.$router.currentRoute.query.page) : 1,
            // 一共多少页
            pageSize: 10,
            // 一共多少条
            total: 10,
            // 增加弹框是否可见
            editFormVisibleForAdd: false,
            // 修改弹框是否可见
            editFormVisibleForUpdate: false,
            // 新增课程的表单数据
            dataForm: {
                name: '',
                desc: '',
                cover: '',
                url: '',
                tags: "",
                calorie: 5000
            },
            // 新增课程时校验数据格式
            dataRules: {
                name: [
                    {require: true, message: "课程的名称不能为空"},
                    {min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur'},
                    {
                        type: "string",
                        required: true,
                        pattern: /^[a-z0-9A-Z\u4e00-\u9fa5]$/,
                        message: '字符只能是中文，英文和数字'
                    }
                ],
                desc: [
                    {require: true, message: "描述不能为空"}
                ],
                cover: [
                    {require: true, message: "课程封面不能为空"}
                ],
                url: [
                    {require: true, message: "课程视频地址不能为空"}
                ],
                tags: [
                    {require: true, message: "课程标签不能为空"}
                ],
                calorie: [
                    {require: true, message: "课程的卡路里不能为空"},
                    {type: 'number', message: '卡路里必须为数字值'}
                ]
            },
            // 选择控件中的选项
            options: [
                {
                    value: "有氧减脂",
                    label: '有氧减脂'
                },
                {
                    value: "核心力量",
                    label: '核心力量'
                },
                {
                    value: "无氧塑型",
                    label: '无氧塑型'
                },
                {
                    value: "下肢增强",
                    label: '下肢增强'
                }
            ],
            value: '',
            // 表格加载时的动态
            dataListLoading: false,
            //批量删除数组
            dataList:[],
            //每一行的id
            id:1,
            //不显示弹窗的关闭按钮
            isClose:false,
            //搜索
            search:'',
            //课程封面的路径
            pathes:[],
            //文件列表
            fileList:[],
            //搜索的课程名称
            name:'',
            //加载
            loading:false
        }
    },
    mounted() {
        let that = this
        that.getDataList()
        console.log(that.getDataList())
    },
    methods: {
        // 加载表格
        getDataList() {
            this.dataListLoading = true;
            let that = this
            let page = that.$router.currentRoute.query.page;
            if (!page) {
                page = 1;
            }
            let url = 'course?page=' + page;
            that.$http.get(url).then(resp => {
                console.log(resp)
                that.tableData = resp.data.data.list
                for (let e of that.tableData) {
                    let startIndex = e.tags.indexOf('["') + 2;
                    let endIndex = e.tags.indexOf('"]');
                    if (startIndex !== -1 && endIndex !== -1) {
                        let result = e.tags.substring(startIndex, endIndex);
                        e.tags = result
                    } else {
                        console.log('未找到匹配的字符串');
                    }
                }
                that.currentPage = resp.data.data.currentPage
                that.pageSize = resp.data.data.pageSize
                that.total = resp.data.data.total
                this.dataListLoading = false;
            })
        },
        // 切换分页
        changePage(page) {
            this.$router.replace('?page=' + page);
            this.getDataList();
        },
        // 新增课程
        addCourse() {
            let that = this
            that.editFormVisibleForAdd = true
        },
        // 确认新增课程
        handleAdd() {
            console.log(this.dataForm)
            let that = this
            let url = '/course/add-course/'
            that.$http.post(url, that.dataForm).then(resp => {
                if (resp.data.code == 200) {
                    this.$message({
                        message: resp.data.msg,
                        type: 'success'
                    });
                    that.dataForm.name = ''
                    that.dataForm.desc = ''
                    that.dataForm.cover = ''
                    that.dataForm.url = ''
                    that.dataForm.tags = ''
                    that.dataForm.calorie = 100
                    that.editFormVisibleForAdd = false
                    that.getDataList()
                } else {
                    this.$message.error(resp.data.msg)
                }
            })
        },
        // 取消新增课程
        cancleAdd(){
            let that = this
            that.dataForm.name = ''
            that.dataForm.desc = ''
            that.dataForm.cover = ''
            that.dataForm.url = ''
            that.dataForm.tags = ''
            that.dataForm.calorie = 100
            that.editFormVisibleForAdd = false
        },
        // 根据课程的id删除课程
        deleteRow(id) {
            this.$confirm(`确认要删除选中的记录吗?【注意批量删除只能批量删除一页的数据】`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let that = this
                let url = "/course/delete-courses/"
                if(id instanceof Array){
                    //从COS中删除对应id的cover
                    let covers=[]
                    for (let i=0;i<id.length;i++){
                        covers[i] = id[i].cover
                    }
                    this.$http.post('cos/deleteCosFile',{pathes: covers})
                    //从COS中删除对应id的video
                    let videos=[]
                    for (let i=0;i<id.length;i++){
                        videos[i] = id[i].url
                    }
                    this.$http.post('cos/deleteCosFile',{pathes:videos })
                    //从数据库中删除对应id的实体
                    let arr=[]
                    for(let i=0;i<id.length;i++){
                        arr[i] = id[i].id
                    }
                    that.$http.post(url, arr).then(resp => {
                        if (resp.data.code == 200) {
                            that.$message.success(resp.data.msg)
                        } else {
                            that.$message.error(resp.data.msg)
                        }
                        that.getDataList();
                    })
                }else {
                    that.$http.post(url, [id]).then(resp => {
                        if (resp.data.code == 200) {
                            that.$message.success(resp.data.msg)
                        } else {
                            that.$message.error(resp.data.msg)
                        }
                        that.getDataList();
                    })
                }
            }).catch(error => {
            });
        },
        //获取批量删除课程的id
        selectionChangeHandle(ids) {
            this.dataList = ids
            console.log(ids)
        },
        //批量删除课程
        deleteRows(ids){
            this.deleteRow(ids)
        },
        //修改课程
        updateRow(id){
            this. editFormVisibleForUpdate= true
            // 请求获取数据
            let that = this
            let url = '/course/id/'+id
            that.$http.get(url).then(resp => {
                if (resp.data.code == 200) {
                    that.dataForm.name = resp.data.data.name
                    that.dataForm.desc = resp.data.data.desc
                    that.dataForm.cover = resp.data.data.cover
                    that.dataForm.url = resp.data.data.url
                    that.dataForm.tags = resp.data.data.tags
                    let startIndex = that.dataForm.tags.indexOf('["') + 2;
                    let endIndex = that.dataForm.tags.indexOf('"]');
                    if (startIndex !== -1 && endIndex !== -1) {
                        let result = that.dataForm.tags.substring(startIndex, endIndex);
                        that.dataForm.tags = result
                        console.log(result);
                    } else {
                        console.log('未找到匹配的字符串');
                    }
                    that.dataForm.calorie = resp.data.data.calorie
                } else {
                    this.$message.error(resp.data.msg)
                }
            })
           that.id = id
        },
        //确认修改课程数据
        handleUpdate(id){
            let that = this
            let url = "/course/update-course"
            that.dataForm.id = that.id
            that.$http.post(url,that.dataForm).then(resp=>{
                if(resp.data.code==200){
                    this.$message({
                        message: "修改成功",
                        type: 'success'
                    });
                    that.dataForm.name = ''
                    that.dataForm.desc = ''
                    that.dataForm.cover = ''
                    that.dataForm.url = ''
                    that.dataForm.tags = ''
                    that.dataForm.calorie = 100
                    that.editFormVisibleForUpdate = false
                    that.getDataList()
                }else {
                    this.$message.error("修改出现问题请稍后尝试")
                }
            })
        },
        //取消修改
        cancleUpdate(id){
            let that = this
            that.dataForm.name = ''
            that.dataForm.desc = ''
            that.dataForm.cover = ''
            that.dataForm.url = ''
            that.dataForm.tags = ''
            that.dataForm.calorie = 100
            that.editFormVisibleForUpdate = false
        },
        //手动刷新
        refresh(){
            this.dataListLoading = true;
            setTimeout(() => {
                this.getDataList()
                this.dataListLoading = false;
            }, 2000);
        },
        // 搜索
        searchHandle(){
            let that = this
            //先执行表单验证
            this.$refs['dataForm'].validate(valid =>{
                if(valid){
                    this.$refs['dataForm'].clearValidate();
                    if(this.name == ''){
                        that.dataForm.name == null;
                    }
                    if(this.pageIndex != 1){
                        that.pageIndex = 1;
                    }
                    that.searchList();
                }else{
                    return false;
                }
            });
        },
        // 搜索结果列表
        searchList(){
            let that = this
            this.dataListLoading = true;
            let data = {
                pageNum: that.pageIndex,
                pageSize: that.pageSize,
                name :that.name
            };
            this.$http.post('/course/search-list',data).then(resp =>{
                    let page = resp.data.page
                    that.tableData = page.list
                    for (let e of that.tableData) {
                        let startIndex = e.tags.indexOf('["') + 2;
                        let endIndex = e.tags.indexOf('"]');
                        if (startIndex !== -1 && endIndex !== -1) {
                            let result = e.tags.substring(startIndex, endIndex);
                            e.tags = result
                        } else {
                            console.log('未找到匹配的字符串');
                        }
                    }
                    that.total = page.total
                    that.pageSize = page.pageSize
                    that.dataListLoading = false
                });
            console.log(that.dataList)
        },
        //上传课程封面
        beforeUploadHandle(file){
            this.loading=true
            const formData = new FormData();
            formData.append('files', file);
            formData.append('type', 'course_photo')
            // 设置请求头
            const config = {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            };
            this.$http.post('/cos/uploadCosFile', formData, config).then(resp => {
                this.loading=false
                this.dataForm.cover = resp.data.urls[0];
                this.pathes = resp.data.pathes;
                this.disabled = true
                this.$message({
                    message: '上传成功',
                    type: 'success',
                    duration: 1200
                })
            })
            return false
        },
        //重新上传课程封面
        removeHandle(){
            console.log(this.dataForm.cover)
            this.$http.post('cos/deleteCosFile',{pathes: [this.dataForm.cover]}).then(resp=>{
                if (resp.data.code==200){
                    this.dataForm.cover=''
                }
            });
        },
        //上传视频
        uploadHandle(file){
            this.loading=true
            const formData = new FormData();
            formData.append('files', file);
            formData.append('type', 'course_video')
            // 设置请求头
            const config = {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            };
            this.$http.post('/cos/uploadCosFile', formData, config).then(resp => {
                this.dataForm.url = resp.data.urls[0];
                this.loading = false
                this.$message({
                    message: '上传成功',
                    type: 'success',
                    duration: 1200
                })
            })
            return false
        },
        // 重新上传视频
        removeVideo(){
            console.log(this.dataForm.url)
            this.$http.post('cos/deleteCosFile',{pathes: [this.dataForm.url]}).then(resp=>{
                if (resp.data.code==200){
                    this.dataForm.url=''
                }
            });
        },
    }
}
</script>
<style lang="less">
.table {
  margin-top: 20px;
}
</style>